package com.gt.util.upload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import com.gt.util.common.DateUtils;
import com.gt.util.common.HttpClientUtils;

/**
 * @ClassName: ImageUtils
 * @author: 刘晨豪
 * @date: 2017年7月20日
 */
public class ImageUploadUtil {

    /**
     * springMVC接收文件
     * 
     * @param myfile
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     * @author: 刘晨豪
     * @date: 2017年7月24日
     */
    public static String UploadMultipartFile(MultipartFile myfile, HttpServletRequest request)
            throws IllegalStateException, IOException {

        String today = DateUtils.getToday();
        String realPath = request.getSession().getServletContext().getRealPath("/upload" + "/" + today);// 获取项目根路径
        File file = new File(realPath);
        // 如果不存在，则创建它
        if (!file.exists()) {
            file.mkdir();
        }
        String newFileName = null;
        if (myfile == null || myfile.isEmpty()) {
            System.out.println("文件未上传");
        } else {
            String uuid = UUID.randomUUID().toString().replace("-", "");// UUID解决的文件同名问题。乱码问题
            String oldName = myfile.getOriginalFilename();
            String ext = oldName.substring(oldName.lastIndexOf("."));
            // 组合成新的文件名
            newFileName = new StringBuffer(uuid).append(ext).toString();

            // 这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，
            myfile.transferTo(new File(realPath + "/" + newFileName));
        }
        return new StringBuffer(today).append("/").append(newFileName).toString();
    }

    /**
     * 上传base64图片
     * 
     * @param request
     * @param base64Data
     * @return 日期+新文件名
     * @author: 刘晨豪
     * @throws Exception
     * @date: 2017年7月21日
     */
    public static String uploadBase64Image(HttpServletRequest request, String base64Data) throws Exception {

        String dataPrix = "";// 图片格式
        String data = "";// 图片内容
        if (StringUtils.isBlank(base64Data)) {
            throw new Exception("上传失败，上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception("上传失败，数据不合法");
            }
        }

        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix) 
                || "data:image/jpg;".equalsIgnoreCase(dataPrix)) {// 编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {// 编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {// 编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {// 编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }

        // 因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        //限制文件大小为4m以内
        if(bs.length > 8*1024*4){
            throw new Exception("图片文件大小必须在4M以内！");
        }
        
        String today = DateUtils.dateToString(new Date(), "yyyyMMdd");// 以日期分组
        String realPath = request.getSession().getServletContext().getRealPath("/upload" + "/" + today);// 获取项目根路径
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }
        // String realPath = request.getServletContext().getRealPath("/upload");//报错
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 新文件名格式：项目根路径+upload+日期+uuid+后缀名
        String newFileName = new StringBuffer(uuid).append(".").append(suffix).toString();
        System.out.println("文件保存至：" + newFileName);
        try {
            // 使用apache提供的工具类操作流
            FileUtils.writeByteArrayToFile(new File(realPath + "/" + newFileName), bs);
        } catch (Exception ee) {
            throw new Exception("上传失败，写入文件失败，" + ee.getMessage());
        }
        System.out.println("-----------正常" + newFileName);
        return new StringBuffer(today).append("/").append(newFileName).toString();
    }

    public static String uploadFileData(HttpServletRequest request, String fileData) throws Exception {

        String suffix = ".jpg";

        String today = DateUtils.getToday();// 以日期分组
        String realPath = request.getSession().getServletContext().getRealPath("/upload" + "/" + today);// 获取项目根路径
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 新文件名格式：项目根路径+upload+日期+uuid+后缀名
        String newFileName = new StringBuffer(uuid).append(".").append(suffix).toString();
        System.out.println("文件保存至：" + newFileName);
        // 使用apache提供的工具类操作流
        FileUtils.writeByteArrayToFile(new File(realPath + "/" + newFileName), fileData.getBytes());
        System.out.println("-----------正常" + newFileName);
        return new StringBuffer(today).append("/").append(newFileName).toString();
    }

    /**
     * 根据网络地址保存图片
     * 
     * @param destUrl 网络地址
     * @param filePath 图片存储路径
     * @throws IOException 
     */
    public static String uploadFileFromUrl(HttpServletRequest request, String sourceUrl) throws IOException {
        InputStream inputStream = null;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        try {
            Map<String, Object> map = HttpClientUtils.doGetFile(request, sourceUrl);
            if (null != map || !map.isEmpty()) {
                String suffix = (String) map.get("suffix");
                inputStream = (InputStream) map.get("inputStream");
                String today = DateUtils.getToday();// 以日期分组
                String realPath = request.getSession().getServletContext()
                        .getRealPath("/upload" + "/" + today);// 获取项目根路径
                File file = new File(realPath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String uuid = UUID.randomUUID().toString().replace("-", "");
                // 新文件名格式：项目根路径+upload+日期+uuid+后缀名
                String newFileName = new StringBuffer(uuid).append(suffix).toString();
                bis = new BufferedInputStream(inputStream);
                fos = new FileOutputStream(realPath + "/" + newFileName);
                while ((size = bis.read(buf)) != -1) {
                    fos.write(buf, 0, size);
                }
                fos.flush();
                return today + "/" + newFileName;
            }
        } finally {
            fos.close();
            bis.close();
            inputStream.close();
        }
        return null;
    }
}
